/* ***********************************************************************
 * UrbanRemix 1.0
 *  last updated 7/22/2009 by Andrew Roberts
 *  andrew.roberts@gatech.edu
 *
 *
 * Classes:
 *
 * UrbanRemix.java 			- main class
 *
 * WavIO.java 				- class (separate thread) that handles recording
 *						 	  of raw audio to 'temp' folder and conversion
 *                             to WAV format
 *
 * CameraPreview.java		- class that handles camera capture in JPG format
 *                             and saves files to 'temp' folder
 *
 * TagSelection.java		    - class that accesses PHP script and populates 
 *
 * HttpFileUploader.java	    - class (separate thread) that handles file
 *							  upload of contents of 'queue' directory
 *
 * 
 * Resources:
 *
 * layout / main.xml		- UI displayed by UrbanRemix class
 * layout / snapshot.xml	- UI displayed by CameraPreview class
 * layout / tag.xml			- UI displayed by TagSelection class
 *
 *
 *
 * ***********************************************************************/

package com.android.UrbanRemix;

import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.TimeZone;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.Menu;

import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class UrbanRemix_New extends Activity {
	// ------------
	// vars for GPS...
	LocationManager locationManager;
	double lat, lng, acc;
	static final int RECORD = 0;
	static final int TAKE_SNAPSHOT = 1;
	static final int REVIEW_QUEUE = 2;

	static final int EXIT = 3;
	// ------------
	// ...for network i/o
	public String username;
	public String password;

	String muploadUrlString;
	public static final String TAGS_XML = "http://urbanremix.lcc.gatech.edu/tags_xml.php";
	public static final String MUPLOAD = "http://urbanremix.lcc.gatech.edu/mupload.php";
	HttpFileUploader qUploader;
	Request rq;
	public int testvar;

	static final int CHOOSE_TAGS_REQUEST = 0;
	static final int SNAPSHOT_REQUEST = 1;
	Context myContext;

	// -------------
	// ...for saving preferences on exit / on load
	public static final String MYPREFS = "mySharedPreferences";
	UploadFunctionality uploadsave;
	// -------------
	// ...and for UI
	TextView introText, intro, welcome, userentry;
	Button reviewUploadQueueButton, startButton; // reviewButton, recordButton,
													// playButton,
													// snapshotButton,
													// uploadButton;
	private String externalMediaPath, localAudioPath;
	boolean recording = false;
	boolean recorded = false;
	boolean playing = false;
	private File rawFileName, wavFileName;
	private String folderPath, tempFolderPath, queueFolderPath,
			userChoiceFolderPath;
	private File folder, tempFolder, queueFolder, userChoiceFolder;

	// -------------
	// called when the app is terminated,
	// to make sure the username and password are saved

	// -------------
	// called when the app launches -- i.e., onCreate() --
	// to retrieve the username and password from a previous session

	// ------------
	// when the app terminates, remember the preferences (i.e., username and
	// password)
	// for next time...

	URLConnection urlConn;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		externalMediaPath = Environment.getExternalStorageDirectory()
				.getAbsolutePath();

		folderPath = externalMediaPath + "/urbanremix";
		tempFolderPath = folderPath + "/temp";
		queueFolderPath = folderPath + "/queue";
		userChoiceFolderPath = folderPath + "/userchoice";

		super.onCreate(savedInstanceState);
		setContentView(R.layout.welcome);

		int mode = Activity.MODE_PRIVATE;
		SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS,
				mode);

		SharedPreferences.Editor editor = mySharedPreferences.edit();

		editor.putString("flag", "0");
		editor.putString("flag_edit", "0");
		editor.commit();

		// -----------
		// define variables for UI elements

		startButton = (Button) findViewById(R.id.Start);
		reviewUploadQueueButton = (Button) findViewById(R.id.Review);
		intro = (TextView) findViewById(R.id.Intro);
		introText = (TextView) findViewById(R.id.IntroText);
		welcome = (TextView) findViewById(R.id.Welcome);

		queueFolder = new File(queueFolderPath);
		folder = new File(folderPath);
		tempFolder = new File(tempFolderPath);
		userChoiceFolder = new File(userChoiceFolderPath);

		myContext = this;

		reviewUploadQueueButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				File[] userChoiceFiles = userChoiceFolder.listFiles();
				int t = userChoiceFiles.length;
				if (t <= 0) {
					Request.notification(myContext, "Error",
							"No files to display");
				} else {

					Intent intent = new Intent(myContext,
							UploadFunctionality.class);
					startActivity(intent);
				}
			}

		});

		startButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				Intent intent = new Intent(myContext, PostSnapShot.class);
				startActivity(intent);
			}

		});

	}

	public boolean onCreateOptionsMenu(Menu menu) {

		menu.add(0, RECORD, 0, "Record");

		menu.add(0, TAKE_SNAPSHOT, 0, "Take Snapshot");

		menu.add(0, REVIEW_QUEUE, 0, "Review Upload Queue");

		menu.add(0, EXIT, 0, "Exit");

		return true;

	}

	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case RECORD:
			Intent intent = new Intent(myContext, PostSnapShot.class);
			startActivity(intent);

			return true;

		case TAKE_SNAPSHOT:
			intent = new Intent(myContext, CameraPreview.class);
			intent.putExtra("tempFolderPath", tempFolderPath);
			startActivity(intent);

			return true;

		case REVIEW_QUEUE:

			intent = new Intent(myContext, UploadFunctionality.class);
			startActivity(intent);

			return true;

		case EXIT:
			Request.notification(myContext, "Image", "X pressed");

			return true;

		}

		return false;

	}

	/*
	 * @Override protected void onDestroy() { uploadsave.savePreferences();
	 * super.onDestroy(); }
	 */

}
